package io.hilo.example.demo.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.hilo.boot.core.UT;
import org.hilo.boot.core.xss.XssHttpServletRequestWrapper;
import org.hilo.boot.scaffold.AbstractPluginGenerator;
import org.hilo.boot.scaffold.FastDfsPluginGenerator;
import org.hilo.boot.scaffold.ScaffoldGenerator;
import org.hilo.boot.scaffold.ScaffoldGeneratorMultiModule;

/**
 * Controller Demo
 * 
 * @author zollty
 * @since 2018-3-12
 */
@Controller
@RequestMapping("/app/gen2")
public class GeneratorController2 {
    
    
    /**
     * 生成代码
     */
    @RequestMapping(value = "/by-type", method= {RequestMethod.POST, RequestMethod.GET})
    public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取表名，不进行xss过滤
        HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);
        String useType = orgRequest.getParameter("useType");
        if(UT.Str.isBlank(useType)) {
            return;
        }
        String groupId = orgRequest.getParameter("groupId");
        String artifactId = orgRequest.getParameter("artifactId");
        String basePackage = orgRequest.getParameter("basePackage");
        if(UT.Str.isBlank(groupId)) {
            groupId = "com.zollty.hilo";
        }
        if(UT.Str.isBlank(artifactId)) {
            artifactId = "project";
            if(UT.Str.isBlank(basePackage)) {
                basePackage = groupId + artifactId;
            }
        }
        
        ScaffoldGenerator generator;
        String structure = orgRequest.getParameter("structure");
        if (ScaffoldGenerator.STRUCT_MULTI.equalsIgnoreCase(structure)) {
            // 域名：groupId， 项目名：artifactId， 基础包名：basePackage
            generator = new ScaffoldGeneratorMultiModule(groupId, artifactId, basePackage);
            generator.setSource("D:/__SYNC2/git/hilo/hilo-demo/hilodemo-multi-module");
        } else {
            generator = new ScaffoldGenerator(groupId, artifactId, basePackage);
            generator.setSource("D:/__SYNC2/git/hilo/hilo-demo/hilodemo-mini-parent");
        }
        
        generator.setUseType(useType);
        if (ScaffoldGenerator.STRUCT_SPLIT.equalsIgnoreCase(structure)) {
            generator.setSeparateBizApp(true);
        } else {
            generator.setSeparateBizApp(false);
        }
        
        
        
        String[] compList = request.getParameterValues("compList[]");
        if (compList != null) {
            for(String comp: compList) {
                if("fdfs".equals(comp)) {
                    AbstractPluginGenerator fastdfsPlugin = new FastDfsPluginGenerator();
                    fastdfsPlugin.setSource("D:/__SYNC2/git/xxx/xxx-commons/fastdfs/fastdfs-spring-boot-starter-demo");
                    generator.addPluginGenerator(fastdfsPlugin);
                }
            }
        }
        
        byte[] data = generator.generatorFile();
        
        if (data == null) {
            return;
        }

        // response.reset();

//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT, OPTIONS");
//        /**
//         * Access-Control-Max-Age gives the value in seconds for how long the response to the
//         * preflight request can be cached for without sending another preflight request.
//         * In this case, 86400 seconds is 24 hours. Note that each browser has a maximum internal value
//         * that takes precedence when the Access-Control-Max-Age is greater.
//         * See also: 浅谈preflight request（预请求）: https://www.jianshu.com/p/b55086cbd9af
//         */
//        response.setHeader("Access-Control-Max-Age", "86400");
//        response.setHeader("Access-Control-Allow-Headers", "*");
//        response.setHeader("Cache-Control", "no-cache");

        response.setHeader("Content-Disposition", "attachment; filename=\"" + artifactId + "-project.zip\"");
        response.addHeader("Content-Length", String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

}
